const app = getApp()
const http = require('../../../utils/util')
const Base64 = require('../../../utils/base')
const time_data = require("../../../utils/data.js")
const localData = require("../../../utils/localData")
const {baseurl} = require('../../../utils/util')
// const { uniqueSort } = require('jquery')
Page({

  /**
   * 页面的初始数据
   */
  data: {
	baseurl:baseurl,
	focusIndex:0,
    date_tyle:1,
    store_id: '',
    store_img: [],
    store_details: '',
    closeer: true,
    weekday: '',
    limit:"",
    multiArray: "",
    type: null,
    show: true,
    userList: [],
	isSubOrder:false,
    date_time: '',
	datatime: "",
	subSeat:'',//我的预约数据
	radioValue: '10', // 默认选中十位数
	proupClass:'none',//图标弹出层显示隐藏
	icon_state:'',//图标说明
	store_flag:false,// 到点指引图是否显示
	activityClass:'none',// 活动轮播弹出层显示隐藏
	isOpenStore:false, //是否正在打开柜门
	wx_show:'none',  //微信二维码显示隐藏
	storageList:[],  //储物柜列表信息
	current_store_id:-1,  //用户没有自己的储物柜时，选中的储物柜id
	pwdVal:[], //验证码显示
	isAuthSavePhoto: false,   //（用来控制显示哪个按钮） false表示还没首次进行弹框授权，或者已经授权了；true表示在首次授权弹框时拒绝授权，或者在设置页面还是拒绝了授权
	
	//选座位参数
	seat_params:{
		store_id:'',
		start_date:'',
		end_date:'',
		currentDate:'',
		start_hours:'',
		end_hours:'',
		shop_start_time:'',
		shop_end_time:'',
		location_img:'',
		store_money:''
	},
	
	// 会议室参数
	room_params:{
		start_date:'', //预约开始日期（2022-02-23）
		end_date:'',   //预约结束日期（2022-02-23）
		start_hours:'',      //预约开始时间（08:00:00）
		end_hours:'',        //预约结束时间（12:00:00）
		store_id:'',
		shop_start_time:'', //门店营业开始时间
		shop_end_time:'' ,//门店营业结束时间
		currentDate:'',
		store_money:''
	},
	timeList:[],//json时间段数据
	newTimeList:[],
	list:[],
	seatActive:-1, //控制预定座位按钮样式 (4小时，8小时)
	roomActive:-1, //控制预定会议室按钮样式 (2小时,4小时，8小时)
  },
  isRestTime:false, //今天是否为临时休息日
  end_date:'', //预定座位最大选择天数
  room_end_date:'',//预定会议室最大选择天数
  loading:false, //加载中
  phoneClass:'none',
  phone:'',
  inputValue:'',
  loading_sure:false, //确认兑换按钮加载状态

  //预定座位修改日期
  changeDate(e){
    this.setData({
      datatime:e.detail.value,
	  seatActive:-1,
	  roomActive:-1,
    })
	//判断今天是否为临时休息日
	this.isTempTime(e.detail.value)
	
    var tamp=time_data.dateToTimestamp(e.detail.value)
    var mapp=time_data.dateToTimestamp(app.globalData.original)
    if(tamp<mapp){
		
    }else if(tamp==mapp){
		// 修改今天为星期几
		let now_day=new Date().getDay()==0?7:new Date().getDay()
		this.setData({
			weekday:now_day
		})
		let timelist=this.data.timeList
		let shop_start=this.data.store_details.start_time
	    let start=time_data.new_hours().start_time
	    let end=this.data.store_details.end_time
	    let startIndex=null
	    let endIndex=null
		let shopStartIndex=null
	    timelist.forEach((item,index)=>{
	    	if(item==start){
	    		startIndex=index
	    	}
	    	if(item==end){
	    		endIndex=index
	    	}
			if(item==shop_start){
				shopStartIndex=index
			}
	    })
	    if(startIndex>=endIndex){
			return this.setData({
            newTimeList:[],
            limit:this.data.store_details.end_time,
            data_end:this.data.store_details.end_time,
			["list[0]"]:[],
			["list[1]"]:[],
          })
      }
	   if(startIndex<shopStartIndex){
		   let n=this.data.date_time+' '+shop_start
		  return this.setData({
			  newTimeList:timelist.slice(shopStartIndex,endIndex+1),
			  limit:shop_start,
			  data_end:time_data.new_hours(n).end_time,
			  ["list[0]"]:timelist.slice(shopStartIndex, endIndex + 1),
			  ["list[1]"]:timelist.slice(shopStartIndex+1, endIndex + 1),
		  })
	  }
	  this.setData({
	    newTimeList:timelist.slice(startIndex,endIndex+1),
	    limit:time_data.new_hours().start_time,
	    data_end:time_data.new_hours().end_time,
		["list[0]"]:timelist.slice(startIndex, endIndex + 1),
		["list[1]"]:timelist.slice(startIndex+1, endIndex + 1),
	  })
      
    }else if(tamp>mapp){
		let pickerDate=this.data.datatime?this.data.datatime:this.data.date_time //当前选择器日期
		let now_day=new Date(pickerDate).getDay()==0?7:new Date(pickerDate).getDay()
		this.setData({
			weekday:now_day
		})
		let timelist=this.data.timeList
		 let start=this.data.store_details.start_time
		let start_h=start.split(':')[0].length==1?'0'+start.split(':')[0]:start.split(':')[0]
		let start_m=start.split(':')[1]
		let newStart=start_h+':'+start_m
	    let end=this.data.store_details.end_time
	    let startIndex=null
	    let endIndex=null
	    timelist.forEach((item,index)=>{
	    	if(item==newStart){
	    		startIndex=index
	    	}
	    	if(item==end){
	    		endIndex=index
	    	}
	    })
      let begin_time=new Date(e.detail.value+' '+this.data.store_details.start_time)
      let end_time=new Date(begin_time.getTime()+1000*60*30)
      let end_hours=end_time.getHours()==0?'0'+end_time.getHours():end_time.getHours()
	  let end_m=time_data.new_hours(this.data.datatime+' '+this.data.store_details.start_time).end_time
      this.setData({
        newTimeList:timelist.slice(startIndex,endIndex+1),
        limit:newStart,
        data_end:end_m,
		["list[0]"]:timelist.slice(startIndex, endIndex + 1),
		["list[1]"]:timelist.slice(startIndex+1, endIndex + 1),
      })
    }
  },
  onRadioChange(e) {
    this.setData({	
      radioValue: e.detail.value
    })
  },
  //门店详情
  getStore: function () {
    const _this = this
    let data = {
      user_id: wx.getStorageSync('user_id'),
      user_token: wx.getStorageSync('user_token'),
      store_id: _this.data.store_id
    }
    http.post('store/storeDetail',Base64.encode(JSON.stringify(data))).then(res => {
      if(res.status == 1) {
        var number = res.result.start_time
        number = number.split(":")
        _this.setData({
		  isSubOrder:true,
          store_img: res.result.store_img,
          store_details: res.result,
		  end_date: time_data.data_time(2,res.result.make_date),
		  room_end_date:time_data.data_time(2,res.result.room_make_date),
		  ['seat_params.shop_start_time']:res.result.start_time,
		  ['seat_params.shop_end_time']:res.result.end_time,
		  ['room_params.shop_start_time']:res.result.start_time,
		  ['room_params.shop_end_time']:res.result.end_time,
        },()=>{
			let timeList=this.data.timeList
			let  now_time =time_data.new_hours().start_time
			let start_h =this.data.store_details.start_time.split(':')[0].length==1?'0'+this.data.store_details.start_time.split(':')[0]:this.data.store_details.start_time.split(':')[0]
			let start_m=this.data.store_details.start_time.split(':')[1]
			let start_time=start_h+':'+start_m
			let nowIndex=null
			let startIndex=null
			timeList.forEach((item,index)=>{
				if(item==now_time){
					nowIndex=index
				}
				if(item==start_time){
					startIndex=index
				}
			})
			// 判断当前时间是否在门店营业时间内
			if(nowIndex<startIndex){
				let date=time_data.data_time(1)+' '+this.data.store_details.start_time
				this.setData({
				  limit:this.data.store_details.start_time,
				  data_end:time_data.new_hours(date).end_time
				},()=>{
					this.ready()
				})
			}else{
				this.setData({
				  limit:time_data.new_hours().start_time,
				  data_end:time_data.new_hours().end_time
				},()=>{
					this.ready()
				})
			}
			//判断今天是否为临时休息日
			this.isTempTime()
		})
      }
    })
  },
  //判断今天是否为临时休息日
  isTempTime(date){
	  let temp_start_time=new Date(this.data.store_details.temp_start_time).getTime()  //临时休息日开始时间（时间戳）
	  let temp_end_time=new Date(this.data.store_details.temp_end_time).getTime()  //临时休息日结束时间（时间戳）
	  let current_time=date?new Date(date).getTime():new Date().getTime() //当前时间戳
	  if(temp_start_time<current_time && current_time<temp_end_time){ //代表今天为临时休息日
	  	this.setData({
	  		isRestTime:true
	  	})
	  }else{
	  	this.setData({
	  		isRestTime:false
	  	})
	  }
  },
  // tab切换
  seach_goods: function (e) {
	let userList=this.data.userList
    userList.forEach((item,index)=>{
		 item.active=false
		 if(index==e.currentTarget.dataset.index){
			 item.active=true
		 }
	 })
	 
	 if(e.currentTarget.dataset.name=='预定座位'){
		 //获取当前选择日期的时间戳
		 let current=new Date(this.data.datatime).getTime()
		 let end=new Date(this.data.end_date).getTime()
		 if(current>end){
			 this.setData({
				 datatime:this.data.end_date
			 })
		 }
	 }
	 if(e.currentTarget.dataset.name=='会议室'){
	 	 //获取当前选择日期的时间戳
	 	 let current=new Date(this.data.datatime).getTime()
	 	 let end=new Date(this.data.end_date).getTime()
	 	 if(current>end){
	 	 this.setData({
	 		 datatime:this.data.end_date
	 	 })
	 	 }
	 }
	 //计算当前日期时间，获取结束时间
	 let data=this.data.datatime+' '+this.data.limit
	 this.setData({
		 userList:userList,
		 type:e.currentTarget.dataset.type,
		 seatActive:-1,
		 roomActive:-1,
		 // data_end:time_data.new_hours(data).end_time,
	 })
  },
  next:function(){
	   let date=this.data.date_time?this.data.date_time:this.data.datatime
	   let startDate=(date.replace(/-/g,'/'))+' '+this.data.limit
	   let endDate=(date.replace(/-/g,'/'))+' '+this.data.data_end
	   let startMS=new Date(startDate).getTime()
	   let endMS=new Date(endDate).getTime()
	   //获取用户选的日期是星期几
	   let prckerDate=this.data.datatime?this.data.datatime:this.data.date_time
	   let userDay=new Date(prckerDate.replace(/-/g,'/')).getDay()
	   userDay=userDay==0?7:userDay
	   //店铺固定休息日
	   let rest_time=this.data.store_details.rest_time
	   if(rest_time.indexOf(userDay)!==-1){
	       return wx.showToast({
	         title: '门店今天暂停营业,请选择其他日期',
	         icon:"none",
	         duration:2500
			})
	   }
	   //店铺临时休息日
	   if(this.data.isRestTime){
		   return wx.showToast({
		     title: `门店今天为临时休息日,请选择其他日期`,
		     icon:"none",
		     duration:2500
		   	})
	   }
	   if(startMS>=endMS){
		   return wx.showToast({
		     title: '此时间段门店已暂停营业或日期格式不正确，请选择其他日期！',
		     icon:"none",
		     duration:2500
		   	})
	   }
	   if(this.data.type==1){ //去往选座位页面
			this.setData({
				['seat_params.store_id']:this.data.store_id,
				['seat_params.start_hours']:this.data.limit,
				['seat_params.end_hours']:this.data.data_end,
				['seat_params.start_date']:this.data.date_time,
				['seat_params.end_date']:this.data.end_date,
				['seat_params.currentDate']:this.data.datatime?this.data.datatime:this.data.date_time,
				['seat_params.location_img']:this.data.store_details.location_img,
				['seat_params.store_money']:this.data.store_details.store_money
			})
			wx.navigateTo({
				url: '/pages/store/seat/seat?seat_params='+JSON.stringify(this.data.seat_params),
			})
		}else{
			app.globalData.form=this.data.store_details
			this.setData({
				['room_params.store_id']:this.data.store_id,
				['room_params.start_hours']:this.data.limit,
				['room_params.end_hours']:this.data.data_end,
				['room_params.start_date']:this.data.date_time,
				['room_params.end_date']:this.data.room_end_date,
				['room_params.currentDate']:this.data.datatime?this.data.datatime:this.data.date_time,
				['room_params.store_money']:this.data.store_details.store_money
			})
			wx.navigateTo({
				url:'/pages/store/door/door?room_params='+JSON.stringify(this.data.room_params)
			})  
        }
  },
  // 隐藏手机号弹出层
  hidePhone(){
  	this.setData({
  		phoneClass:'none'
  	})
  },
  //兑换
  async sure(){
	  let _this=this
	  //判断用户是否登录
	  let user_token = wx.getStorageSync('user_token')
	  if (!user_token) {
	  	wx.showModal({
	  		title: '提示',
	  		content: '你还没有登陆，是否登录?',
	  		success(res) {
	  			if (res.confirm) {
	  				wx.clearStorageSync()
	  				_this.login()
	  			}
	  		}
	  	})
	  	return
	  }
	  
	  //判断用户是否授权手机号
	  let result=await this.getUserInfo()
	  if(result=='nophone'){
	     return this.setData({
	  		phoneClass:'show'
	  	})
	  }
	  
	  
	  
	  let val=this.data.pwdVal
	  if(val.length==0){
		  return wx.showToast({title:'请输入兑换码',icon:'none'})
	  }
	  if(val.length<10){
		  return wx.showToast({title:'兑换码长度不正确',icon:'none'})
	  }
	  
	  
	  let reg=new RegExp(',','g')
	  let str=val.toString()
	  let newstr=str.replace(reg,'')
	  
	  //显示‘确认兑换按钮’加载状态
	  this.setData({
		loading_sure:true
	  })
	  
	  let data={
			user_id:wx.getStorageSync('user_id'),
			user_token:wx.getStorageSync('user_token'),
			store_id:this.data.store_id,
			phone:wx.getStorageSync('phone'),
			code:newstr
	  }
	  http.post('user/exchange',Base64.encode(JSON.stringify(data))).then((res)=>{
			//隐藏加载状态
			this.setData({
				loading_sure:false
			})
			
	  	   if(res.status==1){
			   wx.showToast({
				   title:'兑换成功',
				   icon:'none'
			   })
			   _this.setData({
				   pwdVal:[],
				   inputValue:''
			   })
		   }else{
			   wx.showToast({
			   	title:res.message,
			   	icon:'none'
			   })
		   }
	  })
  },
  
  //获取用户信心
  async getUserInfo(){
	let phone=wx.getStorageSync('phone')  
	if(phone){
		return 'phone'
	}else{
		return 'nophone'
	}
  },
  
  //获取手机号
  getPhoneNumber(e){
	  let _this=this
  	  this.setData({
  		  phoneClass:'none'
  	  })
  	  if(e.detail.errMsg=='getPhoneNumber:ok'){
  	  	wx.login({
  			success:(res)=>{
  				let data={
  					encryptedData:e.detail.encryptedData,
  					code:res.code,
  					iv:e.detail.iv,
  					user_id:wx.getStorageSync('user_id'),
  					user_token:wx.getStorageSync('user_token'),
  				}
  				http.post('user/postPhone',Base64.encode(JSON.stringify(data))).then(res=>{
  					if(res.status==1){
						wx.setStorageSync('phone',res.result)
  						wx.showToast({
  							title:'授权成功',
  							icon:'none'
  						})
  					}else{
  						wx.showToast({
  							title:res.msg,
  							icon:'none'
  						})
  					}
  				})
  			}
  		})
  	  }else{
  	  	wx.showToast({
  	  		title:'授权失败',
  	  		icon:'none'
  	  	})
  	  }
  },
  
  //登录
  login() {
  	wx.login({
  		success(res) {
  			if (res.code) {
  				wx.setStorageSync('code', res.code)
  			} else {}
  		}
  	})
  	const _this = this
  	wx.getUserProfile({
  		desc: '获取用户相关信息',
  		success: function(obj) {
  			let code = wx.getStorageSync('code')
  			var data = {
  				code: code,
  				encryptedData: obj.encryptedData,
  				iv: obj.iv,
  			}
  			http.post('wechat/login', Base64.encode(JSON.stringify(data))).then(res => {
  				if (res.status != 1) {}
  				wx.setStorageSync('user_id', res.result.user_id)
  				wx.setStorageSync('user_token', res.result.user_token)
				wx.setStorageSync('phone', res.result.phone)
  				wx.showToast({
  					title: '登录成功',
  					icon: 'none'
  				})
  
  			})
  		},
  		fail: function(obj) {}
  	})
  },
  
  //重置预约时间段参数
  _initSeatParams(){
	  this.setData({
	  	['seat_params.start_time']:'',
	  	['seat_params.end_time']:'',
	  	['seat_params.date']:'',
	  	['seat_params.start_hours']:'',
	  	['seat_params.end_hours']:''
	  })
  },
  //选择门店返回门店详情时重置日期时间
  _initDate(){
	  this.setData({
		  datatime:time_data.data_time(1)
	  })
  },
  slot:function(e){
	const _this = this
    let endd=""
    var tab = e.currentTarget.dataset.type
    if(tab==2){
       endd = {
        end_time:_this.data.store_details.end_time,
        end_stmap:time_data.time_to_secc(_this.data.store_details.end_time)
      }
    }else{
		let date=app.globalData
		endd=time_data.time_to_list(app.globalData.se_time.start_time,_this.data.store_details.end_time,tab)
		if(_this.data.type==1){ //预定座位时间段
			let startTime=date.date_time+' '+date.se_time.start_time
			let endTime=date.date_time+' '+date.se_time.end_time
			let time=date.date_time
			let start_hours=date.se_time.start_time
			_this.setData({
				['seat_params.start_time']:startTime,
				['seat_params.end_time']:endTime,
				['seat_params.date']:time,
				['seat_params.start_hours']:start_hours,
				['seat_params.end_hours']:endd.end_time
			})
		}else{ //预定会议室时间段
			let make_start_time=date.date_time
			let make_end_time=date.date_time
			let start_time=date.se_time.start_time
			let end_time=endd.end_time
			_this.setData({
				['room_params.make_start_time']:make_start_time,
				['room_params.make_end_time']:make_end_time,
				['room_params.start_time']:start_time,
				['room_params.end_time']:end_time
			})
		}
    }
    app.globalData.time_status=1
    app.globalData.se_time.end_time=endd.end_time
    app.globalData.se_time.end_stamp=endd.end_stmap
    _this.setData({
      active: tab,
      data_end:endd.end_time
    })
  },
  // 遮罩
  close: function () {
    this.setData({
      show: true
    })
  },
  closeer:function(){
    this.setData({
      closeer:true
    })
  },
  shower:function(){
    this.setData({
      closeer:false
    })
  },
  //跳转微信客服
  tofirmwx(){
	  let wechat_link=this.data.store_details.wechat_link
	  wx.openCustomerServiceChat({
		  extInfo:{
			  url:wechat_link
		  },
		  corpId:'ww022673e46dbd4690',
		  success:(res)=>{
        console.log(res);
        wx.showToast({
          title: res,
        })
      },
      fail:(err)=>{
			  console.log(err,'err');
        wx.showToast({
          title: err,
        })
      }
	  })
  },
  //显示图标说明
  showState(e){
	  if(e.currentTarget.dataset.item){
		  let item=e.currentTarget.dataset.item
		  if(item.check==1){
		  		let current= this.data.store_details.store_facility.filter(v=>v.id==item.id)
		  		this.setData({
					 icon_state:current[0].content.replace(/\n/g,"<br/>"),
		  			 proupClass:'show',
					 store_flag:false
		  		})
		  }
	  }else{
		  // 到店指引弹出层
		  this.setData({
			 store_flag:true,
		  	 proupClass:'show'
		  })
	  }
  },
  //隐藏图标说明
  hideState(){
	  this.setData({
	  	proupClass:'hide'
	  })
	  setTimeout(()=>{
		  this.setData({
		  	proupClass:'none'
		  })
	  },200)
  },
  // 活动轮播图显示
  showActivity(){
	  this.setData({
		  activityClass:'show'
	  })
  },
  // 活动轮播图隐藏
  closeActivity(){
	  this.setData({
	  	activityClass:'hide'
	  })
	  setTimeout(()=>{
	  		  this.setData({
	  		  	activityClass:'none'
	  		  })
	  },200)
  },
  //选择储物柜
  changeStore(e){
	//选中储物柜状态为3时提示购买期卡  status==3
	if(e.currentTarget.dataset.item.status==3){
		 wx.showToast({title:'请购买期卡',icon:'none'})
		 return 
	}
	// 如果没有，用户可以选择
	let item=e.currentTarget.dataset.item
	// 判断储物柜状态为1时不可选中
	if(item.status==1) return
	// 将当前选中储物柜status改为2
	if(item.id==this.data.current_store_id){
		this.setData({
			current_store_id:-1
		})
	}else{
		this.setData({
			current_store_id:item.id
		})
	}
  },
  //打开柜门
  openStore(){
	  
	//return false     //9月30日
	
	//获取status==2的储物柜 我的储物柜
	let list=this.data.storageList
	// 之前选中的储物柜
	let myStore= list.filter(v=>v.status==2)
	//现在选中的储物柜
	let currentStore=list.filter(v=>v.id==this.data.current_store_id)
	
	if(currentStore.length==0){
	   wx.showToast({title:'请选择储物柜',icon:'none'})
	   return 
	} 
	
	//如果之前有选中的储物柜和现在选中的作比较， 不同的话提示用户
	if(myStore.length!=0 && myStore[0].id!=currentStore[0].id){
		return wx.showToast({title:`请选择自己的储物柜(${myStore[0].show_number}号)`,icon:'none'})
	}

	
	if(myStore.length!==0){
		//储物柜支付请求
		this.setData({
			current_store_id:myStore[0].id
		})
		this.openStoreMethods()
	}else{
		this.setData({
			current_store_id:currentStore[0].id
		})
		this.openStoreMethods()
	}
   
  },
  //打开柜门请求
  openStoreMethods(){
	// 显示‘打开柜门中...’
	this.setData({
		 isOpenStore:true
	})
	
	// 准备开柜参数
	let data={
			  user_id:wx.getStorageSync('user_id'),
			  user_token:wx.getStorageSync('user_token'),
			  store_id:this.data.store_id, //门店id
			  container_id:this.data.current_store_id  //储物柜id
	}
	
	http.post('store/containerO',Base64.encode(JSON.stringify(data))).then((res)=>{
			  // 关闭‘打开柜门中...’
			  this.setData({
				  isOpenStore:false
			  })
			  wx.showToast({
				  title:res.message,
				  icon:'none'
			  })
			  if(res.status==1){
				  this.setData({
					  current_store_id:-1
				  })
				 this.getStoreList() //获取储物柜列表信息
			  }
	})
  },
  //获取储物柜列表信息
  getStoreList(){
	  let data={
		  user_id: wx.getStorageSync('user_id'),
		  user_token: wx.getStorageSync('user_token'),
		  store_id:this.data.store_id
	  }
	  http.post('store/containerL',Base64.encode(JSON.stringify(data))).then((res)=>{
		  if(res.status==1){
			  this.setData({
				  storageList:res.result
			  })
		  }else{
			  wx.showToast({
				  title:'获取储物柜信息失败',
				  icon:'none'
			  })
		  }
	  })
  },
  //获取我的预约数据
  getMySubmit(){
	  let userList1=[
	  	{ 'id': "5", "active": true, "userName": "我的预约" },
	  	{ 'id': "1", "active": false, "userName": "预订座位" },
	  	{ 'id': "2", "active": false, "userName": "会议室" },
	  	{ 'id': "3", "active": false, "userName": "储物柜" },
	  	{ 'id': "4", "active": false, "userName": "团购劵" },
	  ]
	  let userList2=[
	  	{ 'id': "1", "active": true, "userName": "预订座位" },
	  	{ 'id': "2", "active": false, "userName": "会议室" },
	  	{ 'id': "3", "active": false, "userName": "储物柜" },
	  	{ 'id': "4", "active": false, "userName": "团购劵" },
	  ]
	  
	  let token=wx.getStorageSync('user_token')
	  if(!token){ //用户没有登录
		  return this.setData({
			  userList:userList2,
			  type:1
		  })
	  }
  	  let data={
  	  	user_id: wx.getStorageSync('user_id'),
  	  	user_token: token,
		store_id:this.data.store_id
  	  }
	  http.post('store/appoint',Base64.encode(JSON.stringify(data))).then((res)=>{
			  if(res.status==1){
	  			  let data=res.result
				  if(!data){ //没有预约数据
					  this.setData({
						  userList:userList2,
						  type:1
					  })
				  }else{
					  this.setData({
					  	userList:userList1,
					  	type:5,
						subSeat:data
					  })
				  }
	  		  }else{
				  this.setData({
				  	userList:userList2,
				  	type:1
				  })
	  			  wx.showToast({
	  				  title:res.message,
	  				  icon:'none'
	  			  })
	  		  }
	  })
  },
  //点击开门
  openDoor(){
	
	 let that=this
	 
	 //判断是否距离门店不超过50米
	 
	 wx.getLocation({
	  type: 'gcj02',
	  isHighAccuracy:true,
	  success (res) {
	 	 
	 	 that.setData({
	 	 	loading:true
	 	 },()=>{
	 	 	setTimeout(()=>{
	 	 	that.setData({
	 	 		loading:false
	 	 	}) 
	 	 	},3000)
	 	 })
	 	  let data={
	 	  	user_id: wx.getStorageSync('user_id'),
	 	  	user_token: wx.getStorageSync('user_token'),
	 	  	store_id:that.data.store_id,
	 	 	latitude:res.latitude,
	 	 	longitude:res.longitude
           }
           console.log(data);
	 	  http.post('/store/openDoor',Base64.encode(JSON.stringify(data))).then((res)=>{
	 	 	if(res.status==1){
	 	 		wx.showToast({
	 	 			title:'开门成功',
	 	 			icon:'none'
	 	 		})
	 	 	}else{
	 	 		wx.showToast({
	 	 			title:res.message,
	 	 			icon:'none'
	 	 		})
	 	 	}
	 	  }) 
	 	 
	 	 
	  },
	  fail () {
	 	return wx.showToast({
	 		 title:'获取定位失败',
	 		 icon:'none'
	 	})
	  }
	 })
	 
	 
	 
	 
  },
  //去往选择门店页面
  goShopList(){
	  wx.navigateTo({
		  url:'/pages/shop/shoplist/shoplist'
	  })
  },
  //演示微信客服二维码
  wxshow(){
	  this.setData({
	  	wx_show:'show'
	  })
  },
  //隐藏微信二维码
  wxhide(){
	  this.setData({
	  	wx_show:'hide'
	  })
	  setTimeout(()=>{
	  	this.setData({
	  		wx_show:'none'
	  	})
	  },200)
  },
  //隐藏兑换界面
  hidePayLayer(){
	  let list=this.data.userList
	  list.forEach(v=>{
		  v.id==1?v.active=true:v.active=false
	  })
	  this.setData({
		  type:1,
		  userList:list
	  })
  },
  //拨打电话
  makingCall(e){
	  wx.makePhoneCall({
	    phoneNumber: e.currentTarget.dataset.phone 
	  })
  },
  //导航
  address(){
	  let _this=this
	  wx.getLocation({
	    type: 'gcj02', //返回可以用于wx.openLocation的经纬度
	    success: (res) => {
	      wx.openLocation({
	        latitude: _this.data.store_details.lat-0,//目的地的纬度
	        longitude: _this.data.store_details.lng-0,//目的地的经度
	        name: _this.data.store_details.store_name, //打开后显示的地址名称
			address:_this.data.store_details.address
	      })
	    }
	  })
  },
  //复制微信号
  copyWX(e){
	let _this=this
	wx.setClipboardData({
	  data: _this.data.store_details.wx_code, //复制的数据
	  success: function (res) {
		  //成功
	  }
	})
  },
  //去往帮助中心
  goHelp(){
	  wx.navigateTo({
		  url:'/pages/mine/help/help'
	  })
  },
  //input输入事件
  inputChange(e){

	  if(e.detail.value.length>10) return
	  let str= e.detail.value.replace(/\s+/g,'')
	  let arr= str.split('')
	  this.setData({
		  pwdVal:arr,
		  inputValue:str
	  })
  },
   //input输入事件
  inputChange13(e){
	if(e.detail.value.length>13) return
	let str= e.detail.value.replace(/\s+/g,'')
	let arr= str.split('')
	this.setData({
		pwdVal:arr,
		inputValue:str
	})
},
  inputChange2(e){
	  console.log(111);
	  this.setData({
		  focusIndex:e.currentTarget.dataset.index+1==9?9:e.currentTarget.dataset.index+1
	  })
  },
  
  
   // 保存图片到手机
    onSaveToPhone() {
      this.getSetting().then((res) => {
        // 判断用户是否授权了保存到本地的权限
        if (!res.authSetting['scope.writePhotosAlbum']) {
          this.authorize().then(() => {
            this.savedownloadFile(this.data.store_details.guide_image)
            this.setData({
              isAuthSavePhoto: false
            })
          }).catch(() => {
            wx.showToast({
              title: '您拒绝了授权',
              icon: 'none',
              duration: 1500
            })
            this.setData({
              isAuthSavePhoto: true
            })
          })
        } else {
          this.savedownloadFile(this.data.store_details.guide_image)
        }
      })
    },
    //打开设置，引导用户授权
    onOpenSetting() {
      wx.openSetting({
        success:(res) => {
          console.log(res.authSetting)
          if (!res.authSetting['scope.writePhotosAlbum']) {
            wx.showToast({
              title: '您未授权',
              icon: 'none',
              duration: 1500
            })
            this.setData({// 拒绝授权
              isAuthSavePhoto: true
            })
  
          } else {// 接受授权
            this.setData({
              isAuthSavePhoto: false
            })
            this.onSaveToPhone() // 接受授权后保存图片
  
          }
  
        }
      })
     
    },
    // 获取用户已经授予了哪些权限
    getSetting() {
      return new Promise((resolve, reject) => {
        wx.getSetting({
          success: res => {
			  console.log(res);
            resolve(res)
          }
        })
      })
    },
    // 发起首次授权请求
    authorize() {
      return new Promise((resolve, reject) => {
        wx.authorize({
          scope: 'scope.writePhotosAlbum',
          success: () => {
            resolve()
          },
          fail: res => { //这里是用户拒绝授权后的回调
            console.log('拒绝授权')
            reject()
          }
        })
      })
    },
    savedownloadFile(img) {
      this.downLoadFile(img).then((res) => {
        return this.saveImageToPhotosAlbum(res.tempFilePath)
      }).then(() => {      
      })
    },
    //单文件下载(下载文件资源到本地)，客户端直接发起一个 HTTPS GET 请求，返回文件的本地临时路径。
    downLoadFile(img) {
      return new Promise((resolve, reject) => {
        wx.downloadFile({
          url: img,
          success: (res) => {
            console.log('downloadfile', res)
            resolve(res)
          }
        })
      })
    },
    // 保存图片到系统相册
    saveImageToPhotosAlbum(saveUrl) {
		let _this=this
      return new Promise((resolve, reject) => {
        wx.saveImageToPhotosAlbum({
          filePath: saveUrl,
          success: (res) => {
            wx.showToast({
              title: '保存成功',
              duration: 1000,
			  icon:'none'
            })
            resolve()
			_this.setData({
				proupClass:'none'
			})
          }
        })
      })
    },
    // 弹出模态框提示用户是否要去设置页授权
    showModal(){
      wx.showModal({
        title: '检测到您没有打开保存到相册的权限，是否前往设置打开？',
        success: (res) => {
          if (res.confirm) {
            console.log('用户点击确定')
            this.onOpenSetting() // 打开设置页面          
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
	},

  //预定座位改变时间段
  changeTimeBtn(e){
    let {type,time}=e.currentTarget.dataset
  
    let date=this.data.datatime?this.data.datatime:this.data.date_time
 
	  let d=date.replace(/-/g,'/')
	  let begin_time=new Date(d+' '+this.data.limit)
	  if(type=='seat'){
		  if(time==4){
			  this.setData({
				  seatActive:1
			  })
		  }else if(time==8){
			  this.setData({
			  	  seatActive:2
			  })
		  }else if(time==12){
			  this.setData({
			  	  seatActive:3
			  })
		  }
      let end_time=new Date(begin_time.getTime()+1000*60*60*time)
		  let end_minutes= end_time.getMinutes()?end_time.getMinutes():'00'
		  let end_hours=end_time.getHours()
		  let end_h_m=end_hours+':'+end_minutes
		  let newTimeList=this.data.newTimeList
      let index= newTimeList.findIndex(v=>v==end_h_m)
      console.log("end_time---",end_time)
      console.log("end_minutes---",end_minutes)
      console.log("end_hours---",end_hours)
      console.log("end_h_m---",end_h_m)
      console.log("newTimeList---",newTimeList)
      console.log("index---",index)

		  if(index==-1){
			  this.setData({
			  	data_end:this.data.store_details.end_time,
			  })
		  }else{
			  this.setData({
			  	data_end:end_h_m,
			  })
		  }
	  }else{
		  if(time==2){
		  	this.setData({
		  		roomActive:1
		  	})
		  }else if(time==4){
		  	this.setData({
		  		roomActive:2
		  	})
		  }else if(time==8){
		  	this.setData({
		  		roomActive:3
		  	})
		  }
		  
		  let end_time=new Date(begin_time.getTime()+1000*60*60*time)
		  let end_minutes= end_time.getMinutes()?end_time.getMinutes():'00'
		  let end_hours=end_time.getHours()
		  let end_h_m=end_hours+':'+end_minutes
		  let newTimeList=this.data.newTimeList
		  let index= newTimeList.findIndex(v=>v==end_h_m)
		  if(index==-1){
				this.setData({
					data_end:this.data.store_details.end_time,
				})
		  }else{
		  		this.setData({
		  			data_end:end_h_m,
		  		})
		  }
	  }
  },
  //初始化时间
  ready(){
		let timelist=this.data.timeList
	 	let start=this.data.limit
	 	let end=this.data.store_details.end_time
		let editEnd=time_data.new_hours().end_time
	 	let startIndex=null
	 	let endIndex=null
		let editEdnIndex=null
	 	timelist.forEach((item,index)=>{
	 		if(item==start){
	 			startIndex=index
	 		}
	 		if(item==end){
	 			endIndex=index
	 		}
			if(item==editEnd){
				editEdnIndex=index
			}
	 	})
	 	if(startIndex>=endIndex || editEdnIndex>endIndex){
	     this.setData({
	       newTimeList:[],
	       limit:this.data.store_details.end_time,
	       data_end:this.data.store_details.end_time,
		   ["list[0]"]:[],
		   ["list[1]"]:[],
	     })
	 }else{
	     this.setData({
	       newTimeList:timelist.slice(startIndex,endIndex+1),
		   ["list[0]"]:timelist.slice(startIndex, endIndex + 1),
		   ["list[1]"]:timelist.slice(startIndex+1, endIndex + 1),
	    })
	 }
  },
  //多列选择器
  multiSelector(e){
  	let start_index=e.detail.value[0]
  	let end_index=e.detail.value[1]
  	let start_hours=this.data.list[0][start_index]
  	let end_hours=this.data.list[1][end_index]
  	this.setData({
  		limit:start_hours,
  		data_end:end_hours,
		seatActive:-1,
		roomActive:-1
  	})
  },
  //列改变时触发
  columnchange(e){
  	let list=this.data.list[0]
  	let index=e.detail.value
  	if(e.detail.column==0){ //左边选择列在动
		if(list.length==index+1){
			this.setData({
				['list[1]']:list.slice(index)
			})
		}else{
			this.setData({
				['list[1]']:list.slice(index+1)
			})
		}
  	}
  },
  
  
  
  // 生命周期函数--监听页面加载
  onLoad: function (options) {
    this.setData({
		store_id:options.id,
		timeList:localData.timeList,
	},()=>{
		this.getStore()
		this.getMySubmit()
	})
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
	app.globalData.date_time = time_data.data_time(1)
	app.globalData.end_date =  time_data.data_time(2)
	app.globalData.original = time_data.data_time(1)
	app.globalData.time_status = 0
	this.setData({
	  date_time: time_data.data_time(1),
	  datatime:time_data.data_time(1),
	  active:6,
	})
	app.globalData.se_time=time_data.new_hours()
	
	const _this = this
	var windowHeight = wx.getSystemInfoSync().windowHeight
	var windowWidth = wx.getSystemInfoSync().windowWidth
	var menuButtonInfo = wx.getMenuButtonBoundingClientRect()
	var menuButtonHeight = menuButtonInfo.height //胶囊高度
	var menuButtonTop = menuButtonInfo.top//胶囊距上边界距离
	let today = new Date().getDay();
	if(today === 0) {
	  today = 7
	}
	_this.setData({
	  window_height: windowHeight,
	  padding_top:menuButtonTop,
	  height:menuButtonHeight,
	  windowWidth:windowWidth,
	  weekday: today
	})
	
	// 获取储物柜列表信息
	_this.getStoreList()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
	
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
	
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  goback: function () {
    wx.switchTab({
      url:'/pages/index/index'
    })
  },
  //获取当前日期
  // getNowDate: function (date) {
  //   let timestamp = Date.parse(date)
  //   let date = newDate(timestamp)
  //   let Y = date.getFullYear()
  //   let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1)
  //   let D = date.getDate() < 10 ? '0' + (date.getDate() + 1) : date.getDate() + 1
  //   return (Y + '-')
  // },
})